package com.wwcom.darteagle;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.wwcom.darteagle.data.DartEagleDatabase;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.MatchInfo;
import com.wwcom.darteagle.model.Player;
import com.wwcom.darteagle.util.Settings;
import com.wwcom.darteagle.util.Settings.MatchSettings;


public class HomeActivity extends Activity {
	private DartEagleDatabase db;
	private final GlobalAppData gd= GlobalAppData.getSingletonInstance();
	public static final String RESUME_MATCH= "resumeMatch";
	/**
	 * Simple Dialog used to show the splash screen
	 */
	protected Dialog mSplashDialog;
	
    /** Called when the activity is first created. */	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
	            
       /* Display display = getWindowManager().getDefaultDisplay(); 
        int width = display.getWidth();  // deprecated
        int height = display.getHeight();  // deprecated
        
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        Log.d("HomeActivity", "Display: "+width+", "+height+" at "+metrics.densityDpi+" dpi");
        Log.d("HomeActivity", "DPI:  "+((float)metrics.densityDpi/160.0));
         */
        
    	if (savedInstanceState != null) {
    		if (!savedInstanceState.getBoolean("RESUMING")) {
                showSplashScreen();    			
    		}
    	} else {
            showSplashScreen();
    	}

    	//layout
        setContentView(R.layout.home);

    	TextView sUrl= (TextView)findViewById(R.id.splashAppUrl);
        sUrl.setMovementMethod(LinkMovementMethod.getInstance());
        
//        BugSenseHandler.setup(this, "266abc88");

        //load settings
        Settings.loadSettings(this);

        //database connection
		db= new DartEagleDatabase(this);             	    	
        
    }
    
    @Override
    public void onNewIntent(Intent newIntent) {
    	super.onNewIntent(newIntent);
        //straight back to match if required
        Bundle extras = newIntent.getExtras();
        if(extras !=null)        	
        {
        	boolean resumeMatch= extras.getBoolean(RESUME_MATCH);
        	if (resumeMatch) {
            	if (db == null)
            		db= new DartEagleDatabase(this);
            	resumeMatch();
        	}
        }    	
    }

    
    @Override
    public void onResume() {
    	super.onResume();
    	boolean resumeEnabled;
    	if (gd.match == null)
    		resumeEnabled= db.isResumableMatchInDatabase();
    	else
    		resumeEnabled= !gd.match.isMatchComplete();
    	((Button)findViewById(R.id.resumeMatchButton)).setEnabled(resumeEnabled);    		    	    	
    }
        
    @Override
    public void onDestroy() {
    	super.onDestroy();
    	db.close();
    }
    
    @Override 
    protected void onSaveInstanceState (Bundle outState) {
    	super.onSaveInstanceState(outState);
    	//note that we have been killed by OS so no need to show the splash screen again
    	outState.putBoolean("RESUMING", true);  
    }    
    
    // Listeners
    public void onClickNewMatch(View v) {
        //setup new match
   		gd.matchInfo= new MatchInfo();
		
		//Initialize from stored settings
		Settings.loadSettings(this);
		for (String playerName : MatchSettings.players) {
			gd.matchInfo.addMatchPlayer(new Player(playerName));
		}
		gd.matchInfo.setNumSets(MatchSettings.nSets);
		gd.matchInfo.setNumLegs(MatchSettings.nLegs);
		gd.matchInfo.setLegTarget(MatchSettings.legTarget);
		gd.matchInfo.setDoubleIn(MatchSettings.doubleIn);
		gd.matchInfo.setDoubleOut(MatchSettings.doubleOut);
		gd.matchInfo.setTrebleIn(MatchSettings.trebleIn);
		gd.matchInfo.setTrebleOut(MatchSettings.trebleOut);
		gd.matchInfo.setLoserStarts(MatchSettings.loserStarts);
    			
    	Intent i= new Intent(this,MatchSetupPlayersActivity.class);
    	startActivity(i);
    } 

    public void onClickResumeMatch(View v) {
    	resumeMatch();
    }
    
    public void onClickHelp( View v ) {
        Intent help = new Intent( Intent.ACTION_VIEW , Uri.parse( "http://www.darteagle.org" ) );
        startActivity( help );
    }
    
    public void onClickPlayerHistory( View v ) {
    	Intent i= new Intent(this,PlayerHistoryActivity.class);
    	startActivity(i);    	
    }    
    
    public void onClickPlayerStats( View v ) {
    	Intent i= new Intent(this,PlayerStatsSetupActivity.class);
    	startActivity(i);    	
    }    

    /*public void onClickVenues( View v ) {
    	Intent i= new Intent(this,PlayerStatsActivity.class);
    	startActivity(i);    	
        //Intent help = new Intent( Intent.ACTION_VIEW , Uri.parse( "http://www.darteagle.org/?q=venues" ) );
        //startActivity( help );
    } */   

	//menus
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.darteagle_options_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.menu_options:
        	Intent i= new Intent(this,OptionsActivity.class);
        	startActivity(i);
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    
    private void resumeMatch() {
    	gd.match= db.getResumableMatch();
    	if (gd.match == null) {
    		Toast t= Toast.makeText(this, "No valid match found in database", Toast.LENGTH_LONG);
    		t.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
    		t.show();    		
    		return;
    	}
    	Intent i= new Intent(this,MatchActivity.class);
    	startActivity(i);
    }
    
    // Removes the Dialog that displays the splash screen
    protected void removeSplashScreen() {
        if (mSplashDialog != null) {
            mSplashDialog.dismiss();
            mSplashDialog = null;
        }
    }    
    
    
    // Shows the splash screen over the full Activity
    protected void showSplashScreen() {
        mSplashDialog = new Dialog(this,R.style.SplashScreen);
        mSplashDialog.setContentView(R.layout.splashscreen);
        mSplashDialog.setCancelable(false);
        mSplashDialog.show();
        TextView sUrl= (TextView)mSplashDialog.findViewById(R.id.splashAppUrl);
        sUrl.setMovementMethod(LinkMovementMethod.getInstance());
        
        // Set Runnable to remove splash screen just in case
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
          public void run() {
            removeSplashScreen();
          }
        }, 3000);
    }    
        
}